package com.gusti.admincasa.client.util;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.TrayIcon.MessageType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.gusti.admincasa.client.dto.MessageDto;
import com.gusti.admincasa.client.ui.MessageView;

public class TrayIconViewer implements ActionListener {

	private static TrayIconViewer instance;

	private boolean foundIt = false;
	private TrayIcon trayIcon;
	private String displayMessageTitle = "Admincasa";
	private String trayIconToolTipTitle = "Admincasa";
	private String imagesURL = AdminCasaClientUtil.getServerUrl() + "admincasa/images/";
	private Image defaultImage;
	private Image messageImage;
	private TrayIconViewerThread trayIconViewerThread;
	private MessageView messageView;

	private List<MessageDto> messages = new ArrayList<MessageDto>();

	public static TrayIconViewer getInstance() {
		if ( instance == null ) {
			instance = new TrayIconViewer();
		}
		return instance;
	}

	private TrayIconViewer() {

		if( SystemTray.isSupported() ) {

			SystemTray systemTray = SystemTray.getSystemTray();

			trayIconViewerThread = new TrayIconViewerThread();
			trayIconViewerThread.start();

//			PopupMenu menu = new PopupMenu( "Menu" );
//			MenuItem mostrar = new MenuItem( "Mostrar" );
//			MenuItem ocultar = new MenuItem( "Ocultar" );
//			MenuItem cerrar = new MenuItem( "Cerrar" );

//			mostrar.addActionListener(
//				new ActionListener() {
//					public void actionPerformed( ActionEvent e ) {
//						
//					}
//				}
//			);

//			menu.add( mostrar );
//			menu.addSeparator();
//			menu.add( ocultar );
//			menu.addSeparator();
//			menu.add(cerrar);

			createDefaultImage( "user.png" );

			trayIcon = new TrayIcon( defaultImage );
//			trayIcon.setPopupMenu( menu );
			trayIcon.setToolTip( trayIconToolTipTitle );
			trayIcon.addActionListener( this );
			trayIcon.setImageAutoSize( true );

			try {
				systemTray.add( trayIcon );
				//displayMessage( "Bienvenido", TrayIcon.MessageType.INFO );
			} catch ( AWTException e ) {
				Debug.error( e );
			}

		} else {
			Debug.log( "SystemTray not suported!" );
		}

	}

	public synchronized List<MessageDto> getMessages() {
		return messages;
	}

	public synchronized void addMessages( int messageId, MessageDto messages) {
		foundIt = false;
		for (MessageDto messageDto : this.messages) {
			if( messageDto.getMessageId() == messageId ) {
				foundIt = true;
			}
		}
		if( !foundIt ) {
			this.messages.add( messages );
		}
	}

	private void createDefaultImage( String imageName ) {
		URL url = null;
		try {
			url = new URL( imagesURL + imageName );
		} catch (MalformedURLException e) {
			Debug.error( e );
		}

		Toolkit toolkit = Toolkit.getDefaultToolkit();
		defaultImage = toolkit.createImage( url );
	}

	private void createMessageImage( String imageName ) {
		URL url = null;
		try {
			url = new URL( imagesURL + imageName );
		} catch (MalformedURLException e) {
			Debug.error( e );
		}

		Toolkit toolkit = Toolkit.getDefaultToolkit();
		messageImage = toolkit.createImage( url );
	}

	/**
	 * 
	 * @param message
	 * @param type
	 */
	public void displayMessage( String message, MessageType type ){
		displayMessage( displayMessageTitle, message, type );
	}

	/**
	 * 
	 * @param title
	 * @param message
	 * @param type
	 */
	public void displayMessage( String title, String message, MessageType type ){
		if( !foundIt ) {
			trayIcon.displayMessage( title, message, type );

			if( messageImage == null ) {
				createMessageImage( "mail.png" );
			}

			trayIconViewerThread.play();
		}
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		if( event.getSource() == trayIcon ) {
			trayIconViewerThread.pause();
			trayIcon.setImage( defaultImage );

			while ( getMessages().size() > 0 ) {
				MessageDto messageDto = getMessages().get(0);
				getMessages().remove(0);
				//Debug.showMessage( messageDto.getSenderUserName() + " dice: " + messageDto.getMessage() + "\n" + "el " + messageDto.getSendDate() );
				messageView = new MessageView( messageDto );
				markAsReadMessage( messageDto );
			}
		}
	}

	private void markAsReadMessage( MessageDto messageDto ) {

		try {
			String request = AdminCasaClientUtil.getServerUrl() + "admincasa/rest/markAsReadMessage/" + messageDto.getOwnerUserId() + "/" + messageDto.getMessageId();
			URL url = new URL( request );
			new InputStreamReader( url.openStream() );
		} catch (MalformedURLException e) {
			Debug.error( e );
		} catch (IOException e) {
			Debug.error( e );
		}
	}

	private class TrayIconViewerThread extends Thread {

		private boolean run = false;

		public void play() {
			run = true;
		}

		public void pause() {
			run = false;
		}

		@Override
		public void run() {
			while( true ) {
				if( run ) {
					try {

						trayIcon.setImage( messageImage );
						Thread.sleep( 2000 );
						trayIcon.setImage( defaultImage );
						Thread.sleep( 2000 );

					} catch (InterruptedException e) {
						Debug.error( e );
					}
				}
			}
		}

	}

}
